package com.xiaoq.social.endpoint;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.dubbo.config.annotation.Reference;
import com.xiaoq.apis.interpreter.IInterpreterApi;
import com.xiaoq.apis.interpreter.InterpreterInfo4SocialVo;
import com.xiaoq.apis.sites.ISitesApi;
import com.xiaoq.apis.sites.SitesInfo4SocialVo;
import com.xiaoq.apis.user.IUserApi;
import com.xiaoq.apis.user.UserInfo4SocialVo;
import com.xiaoq.coms.GenericDataResponse;
import com.xiaoq.coms.GenericListResponse;
import com.xiaoq.coms.GenericResponse;
import com.xiaoq.social.entity.FansTagEntity;
import com.xiaoq.social.entity.FollowEntity;
import com.xiaoq.social.service.IFansTagService;
import com.xiaoq.social.service.IFollowService;
import com.xiaoq.social.vo.FollowListVo;
import com.xiaoq.vo.PagingVo;

import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;

@RestController
@RequestMapping("/api/v1/follow")
public class FollowEndPoint {
	
	@Autowired
	private IFollowService followSer;
	
	@Autowired
	private IFansTagService fansTagSer;
	
	@Reference(interfaceClass=ISitesApi.class, check=false, version="1.0.0")
	private ISitesApi sitesDubboApi;
	
	@Reference(interfaceClass=IUserApi.class, check=false, version="1.0.0")
	private IUserApi userDubboApi;
	
	@Reference(interfaceClass=IInterpreterApi.class, check=false, version="1.0.0")
	private IInterpreterApi interpreterDubboApi;
	
	private class UserFollowNums extends GenericDataResponse<Long> {}
	private class UserFollowsList extends GenericListResponse<FollowListVo> {}
	private class UserFollowStatus extends GenericDataResponse<Boolean> {}
	
	private class TgtFollowNums extends GenericDataResponse<Long> {}
	
	private static final Logger LOG = LoggerFactory.getLogger(FollowEndPoint.class);
	
	
	@ApiOperation(value = "关注", notes = "关注")
	@ApiResponses({ @ApiResponse(code = 200, response = GenericResponse.class, message = "关注") })
	@PostMapping(value = "/user/{userId}", produces = { MediaType.APPLICATION_JSON_UTF8_VALUE })
	public ResponseEntity<?> addFollow(@PathVariable(value = "userId", required = false)@ApiParam(value="userId",required=false)String userId,
			@RequestParam(value = "tgtId", required = true) String tgtId,
			@RequestParam(value = "tgtType", required = true) @ApiParam(value="10--景区，11--住宿/宾馆/旅店，12--餐饮/酒店，13--娱乐/KTV，14--超市/购物中心，15--交通运输企业，16--旅行社，20--活动，30--内容，40--讲解员，50--票，60--普通会员",required=true)String tgtType) {
		// 这里需要两个接口
		// 因为关注的时候需要向关注表和粉丝表里面插入目标的信息和user的信息必须有更具userId查user详情
		// 目标Id查目标详情
		// 根据目标类型和目标id将目标的详细信息查询出来
		boolean result = executeFollowMed(userId, tgtId, tgtType);
		if(result){
			return GenericResponse.ok();
		}
		return GenericResponse.ng("没有关注成功！");
	}
	
	
	@ApiOperation(value = "取消关注", notes = "取消关注")
	@ApiResponses({ @ApiResponse(code = 200, response = GenericResponse.class, message = "取消关注") })
	@DeleteMapping(value = "/user/{userId}", produces = { MediaType.APPLICATION_JSON_UTF8_VALUE })
	public ResponseEntity<?> cancelFollow(@PathVariable(value = "userId", required = false) @ApiParam(value="userId",required=false)String userId,
			@RequestParam(value = "tgtId", required = true) String tgtId) {

		// 根据目标Id和和用户Id将关注关系删除
		boolean followResult = followSer.delFollow(userId, tgtId);
		boolean fansTagResult = fansTagSer.delFansTag(userId, tgtId);
		if(followResult&&fansTagResult){
			LOG.info("删除成功！");
			return GenericResponse.ok();
		}
		
		return GenericResponse.ng("删除失败！");
	}
	
	@ApiOperation(value = "(小程序)取消关注", notes = "(小程序)取消关注")
	@ApiResponses({ @ApiResponse(code = 200, response = GenericResponse.class, message = "(小程序)取消关注") })
	@GetMapping(value = "/user/{userId}", produces = { MediaType.APPLICATION_JSON_UTF8_VALUE })
	public ResponseEntity<?> cancelFollowMini(@PathVariable(value = "userId", required = false) @ApiParam(value="userId",required=false)String userId,
			@RequestParam(value = "tgtId", required = true) String tgtId) {

		// 根据目标Id和和用户Id将关注关系删除
		boolean followResult = followSer.delFollow(userId, tgtId);
		boolean fansTagResult = fansTagSer.delFansTag(userId, tgtId);
		if(followResult&&fansTagResult){
			LOG.info("删除成功！");
			return GenericResponse.ok();
		}
		
		return GenericResponse.ng("删除失败！");
	}
	
	@ApiOperation(value = "根据userId查询用户关注总数", notes = "根据userId查询用户关注总数")
	@ApiResponses({ @ApiResponse(code = 200, response = UserFollowNums.class, message = "根据userId查询用户关注总数") })
	@GetMapping(value = "/{userId}/count", produces = { MediaType.APPLICATION_JSON_UTF8_VALUE })
	public ResponseEntity<?> getUserFollowCounts(@PathVariable(value = "userId", required = false)@ApiParam(value="userId",required=false)String userId) {

		// 根据用户Id查询用户关注总数
		Long nums = followSer.findFollowNumsByUser(userId);
		return UserFollowNums.okWithData(nums);
	}
	
	@ApiOperation(value = "查询目标的关注总数", notes = "查询目标的关注总数")
	@ApiResponses({ @ApiResponse(code = 200, response = TgtFollowNums.class, message = "查询目标的关注总数") })
	@GetMapping(value = "/{tgtId}/tgtNum", produces = { MediaType.APPLICATION_JSON_UTF8_VALUE })
	public ResponseEntity<?> getTgtFollowCounts(@PathVariable(value = "tgtId", required = false)@ApiParam(value="tgtId",required=false)String tgtId) {
		Long nums = followSer.findFollowNumsByTgt(tgtId);
		return TgtFollowNums.okWithData(nums);
	}
	
	@ApiOperation(value = "根据userId查询用户关注列表", notes = "根据userId查询用户关注列表")
	@ApiResponses({ @ApiResponse(code = 200, response = UserFollowsList.class, message = "根据目标类型和目标Id调用具体的接口查详情") })
	@GetMapping(value = "/{userId}", produces = { MediaType.APPLICATION_JSON_UTF8_VALUE })
	public ResponseEntity<?> getUserFollowList(@PathVariable(value = "userId", required = false)@ApiParam(value="userId",required=false)String userId,@ModelAttribute(value="pvo")PagingVo pvo) {

		// 根据用户Id查询用户关注列表
		List<FollowEntity> followList = null;
		List<FollowListVo> followListVoList = new ArrayList<>();
		FollowListVo followVo = null;
		if(StringUtils.isNotEmpty(userId)){
			followList = followSer.findFollowListByUser(userId, pvo);
			if(followList.size()!= 0){
				for(FollowEntity follow : followList){
					followVo = new FollowListVo();
					BeanUtils.copyProperties(follow, followVo);
					followListVoList.add(followVo);
				}
				
			}
			
			Long total = (Long) pvo.getTc();
			return UserFollowsList.listAndCount(followListVoList, total);
		}else{
			return GenericResponse.ng("请先登录才可以查询关注列表！");
		}
		
	}
	
	@ApiOperation(value = "是否已经关注", notes = "是否已经关注")
	@ApiResponses({ @ApiResponse(code = 200, response = UserFollowStatus.class, message = "是否已经关注") })
	@GetMapping(value = "/user/{userId}/has", produces = { MediaType.APPLICATION_JSON_UTF8_VALUE })
	public ResponseEntity<?> getFollow(@PathVariable(value = "userId", required = false) @ApiParam(value="userId",required=false)String userId,
			@RequestParam(value = "tgtId", required = true) String tgtId){
		// userId 如果你输入的话就是输的  如果不是就是登陆用户token解析的
		boolean result = followSer.isFollow(tgtId, userId);
		if(result){
			return UserFollowStatus.okWithData(true);
			
		}else{
			return UserFollowStatus.okWithData(false);
		}
		
	}
	
	private boolean executeFollowMed(String userId,String tgtId,String tgtType){
		
		//这里需要调用一个查User详情的接口
		UserInfo4SocialVo userInfo = userDubboApi.getUserInfo4Social(userId);
		if(userInfo!=null){
			userId = userInfo.getId(); 
			String userLogo = userInfo.getLogoUrl(); 
			String userNickName = userInfo.getNickName(); 
			String mobile = userInfo.getMobile();
			String thirdNickName = userInfo.getThirdAccount();
			if(userId !=null){
				
				FollowEntity follow = new FollowEntity();
				FansTagEntity fansTag = new FansTagEntity();
				String targetId = null;
				String targetInfo = null;
				String targetName = null;
				String targetLogo = null;
				String merchantId = null;
				//TODO  显示实现景区的关注后面实体陆续实现
				switch (tgtType) {
				case "10":	
					// 当目标类型是10时,目标Id就是sitesId
					SitesInfo4SocialVo sitesInfo4SocialVo = sitesDubboApi.getSiteInfo4Social(tgtId);
					
					if(sitesInfo4SocialVo!=null){
					
						targetId  = sitesInfo4SocialVo.getId();   
						targetInfo = sitesInfo4SocialVo.getIntroduction(); 
						targetName = sitesInfo4SocialVo.getName(); 
						targetLogo = sitesInfo4SocialVo.getLogo(); 
						merchantId = sitesInfo4SocialVo.getMerchantId(); 
						
						
					}else{
						LOG.error("关注的景区不存在！");
					}
					break;
				case "40":
					//讲解员不需要粉丝维护，只需要一个关注就行了
					InterpreterInfo4SocialVo interpreterInfo = interpreterDubboApi.getInterpreterInfo4Social(tgtId);
					
					if(interpreterInfo!=null){
						targetId  = interpreterInfo.getId();   
						targetInfo = interpreterInfo.getSvcExperience(); 
						targetName = interpreterInfo.getName(); 
						targetLogo = interpreterInfo.getImgUrl(); 
						merchantId = interpreterInfo.getSitesId(); 
					}else{
						LOG.error("关注的讲解员不存在！");
					}
					
					
					break;

				default:
					break;
				}
				
				if(StringUtils.isNotEmpty(targetId)){
					follow.setUserId(userId);
					follow.setUserLogo(userLogo);
					follow.setUserNickName(userNickName);
					follow.setTargetId(targetId);
					follow.setTargetInfo(targetInfo);
					follow.setTargetLogo(targetLogo);
					follow.setTargetName(targetName);
					follow.setTargetType(tgtType);
					follow.setMerchantId(merchantId);
					
					//TODO  用户注册方式一期先不做，user里面的枚举api里面没法获取
					fansTag.setFansAction("");
					fansTag.setTgtId(tgtId);
					fansTag.setMerchantId(merchantId);   // 这个东西景区没有就是空
					fansTag.setTgtType(tgtType);
					fansTag.setUserId(userId);
					fansTag.setUserLogo(userLogo);
					fansTag.setUserMobile(mobile);
					fansTag.setUserNickName(userNickName);
					fansTag.setThirdNickName(thirdNickName);
					
					boolean followResult = followSer.addFollow(follow);
					boolean fansTagResult = fansTagSer.addFansTag(fansTag);
					
					if(followResult&&fansTagResult){
						LOG.info("关注成功！");
						return true;
					}
				}else{
					LOG.error("没有这类目标Id!");
				}
				
			}else{
				LOG.info("没有查到这种会员！");
			}
		}else{
			LOG.error("用户不存在！");
		}
		
		
		
		return false;
	}
	
	

}
